package com.wry.myphotowall.activity;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.imageutils.BitmapUtil;
import com.wry.myphotowall.MyApplication;
import com.wry.myphotowall.R;
import com.wry.myphotowall.adapter.PhotoWallAdapter;
import com.wry.myphotowall.bean.ImageFolder;
import com.wry.myphotowall.dialog.AppSettingsDialog;
import com.wry.myphotowall.dialog.ListImageDirPopupWindow;
import com.wry.myphotowall.fragment.PhotoViewFragment;
import com.wry.myphotowall.fragment.PhotoWallFragment;
import com.wry.myphotowall.listener.OnPhotoDirSelected;
import com.wry.myphotowall.mycutavatar.CutPictureAty;
import com.wry.myphotowall.util.Common;
import com.wry.myphotowall.util.DisplayUtil;
import com.wry.myphotowall.util.ImageCaptureManager;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

public class PhotoPickerActivity extends FragmentActivity {


    /**
     * 默认图片选择数量
     */
    private int mDefaultCount;
    /**
     * 默认搜索路径
     */
    private String mDefaultSearchPath;
    /**
     * 控件
     */
    private RelativeLayout mBarView;
    private TextView tvComplete, tvPreview, tvSelected;
    private ImageView mBackBtn;
    private Button tvChooseAblum;

    private PhotoWallFragment mPickerFragment;
    private PhotoViewFragment mPagerFragment;

    private RelativeLayout mTopbar;//顶部布局
    private RelativeLayout mBottombar;//底部布局

    private View diyView;//自定义顶部间隔view


    private boolean isShowCamera = true;//显示照相
    private boolean isShowCut = false;//图片裁剪


    public final static String KEY_SELECTED_PHOTOS = "SELECTED_PHOTOS";
    public static final int REQUEST_CODE = 200;


    private AppSettingsDialog appSettingsDialog;
    private String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private boolean isShowDialog = false;


    /**
     * 扫描拿到所有的图片文件夹
     */
    private List<ImageFolder> mImageFolders = new ArrayList<>();
    /**
     * 临时辅助类，用于防止同一个文件夹的多次扫描
     */
    private HashSet<String> mDirPaths = new HashSet<String>();
    /**
     * 第一个扫描到的文件夹
     */
    private String firstDirName;
    /**
     * 当前选择的图片文件夹
     */
    private File mImgDir;

    private String mDesireSearchPath;//默认选择的文件夹

    /**
     * 文件夹选择popupwindow
     */
    private ListImageDirPopupWindow mDirPopupWindow;
    /**
     * 选择各类图片文件夹按钮（relayout）
     */
    RelativeLayout layout_bottom_actionbar;

    private int mScreenHeight;//屏幕高度
    private int mScreenWidth;//屏幕宽度

    private ImageCaptureManager captureManager;

    private ProgressDialog mProgressDialog;

    /**
     * 暴露接口
     *
     * @param activity
     * @param maxSelectCount-限制的最大图片选择数量
     * @param searchPath-指定图片搜索路径(若为null-表示搜索所有图片)
     * @param isShowCamera-是否显示照相机按钮
     * @param isShowCut-是否进行图片裁剪
     */
    public static void actionStart(Activity activity, int maxSelectCount, String searchPath, boolean isShowCamera, boolean isShowCut) {
        Intent intent = new Intent(activity, PhotoPickerActivity.class);
        intent.putExtra(PhotoWallFragment.EXTRA_SELECT_COUNT, maxSelectCount);
        intent.putExtra(PhotoWallFragment.EXTRA_DEFAULT_SELECTED_LIST, searchPath);
        intent.putExtra(PhotoWallFragment.SHOWCAMERA, isShowCamera);
        intent.putExtra(PhotoWallFragment.SHOWCUT, isShowCut);
        activity.startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo_wall);

        captureManager = new ImageCaptureManager(this);

        mDefaultCount = getIntent().getIntExtra(PhotoWallFragment.EXTRA_SELECT_COUNT, 9);
        mDefaultSearchPath = getIntent().getStringExtra(PhotoWallFragment.EXTRA_DEFAULT_SELECTED_LIST);
        isShowCamera = getIntent().getBooleanExtra(PhotoWallFragment.SHOWCAMERA, true);
        isShowCut = getIntent().getBooleanExtra(PhotoWallFragment.SHOWCUT, false);

        if (isShowCut) {
            mDefaultCount = 1;
        }


        mScreenHeight = DisplayUtil.getScreenHeight();
        mScreenWidth = DisplayUtil.getScreenWidth();
        initViews();
        if (mPickerFragment == null) {
            DisplayMetrics outMetrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
            mPickerFragment = PhotoWallFragment.newInstance(outMetrics.heightPixels, mDefaultCount, mDefaultSearchPath, isShowCamera, isShowCut);
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, mPickerFragment)
                    .commit();
        }
        initEvents();
    }

    private void initEvents() {
        tvChooseAblum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mDirPopupWindow != null) {
                    mDirPopupWindow.setAnimationStyle(R.style.anim_popup_dir);
                    mDirPopupWindow.showAtLocation(layout_bottom_actionbar, Gravity.BOTTOM, 0, getResources().getDimensionPixelSize(R.dimen.actionBarHeight));
                    //设置背景颜色变暗
                    WindowManager.LayoutParams lp = getWindow().getAttributes();
                    lp.alpha = .3f;
                    getWindow().setAttributes(lp);
                }
            }
        });
        //初始化按钮
        if (PhotoWallAdapter.mSelectedImage == null ||
                PhotoWallAdapter.mSelectedImage.size() <= 0) {
            tvPreview.setText(R.string.preview);
            tvPreview.setEnabled(false);
            tvComplete.setText(R.string.action_done);
            tvComplete.setEnabled(false);
            tvComplete.setPadding(getResources().getDimensionPixelSize(R.dimen.x14), 0, getResources().getDimensionPixelSize(R.dimen.x14), 0);
        } else {
            tvPreview.setText(getResources().getString(R.string.preview)
                    + "(" + PhotoWallAdapter.mSelectedImage.size() + ")");
            tvPreview.setEnabled(true);
            tvComplete.setText(String.format("%s(%d/%d)", getString(R.string.action_done),
                    PhotoWallAdapter.mSelectedImage.size(), mDefaultCount));
            tvComplete.setEnabled(true);
            tvComplete.setPadding(getResources().getDimensionPixelSize(R.dimen.x6), 0, getResources().getDimensionPixelSize(R.dimen.x6), 0);
        }
        //监听预览按钮
        tvPreview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int[] screenLocation = new int[2];
                v.getLocationOnScreen(screenLocation);
                PhotoViewFragment fragment =
                        PhotoViewFragment.newInstance(PhotoWallAdapter.mSelectedImage, 0, mDefaultCount, screenLocation,
                                v.getWidth(), v.getHeight());
                addPhotoPagerFragment(fragment);
            }
        });
        tvComplete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isShowCut) {//需要裁剪
                    Intent intent = new Intent(PhotoPickerActivity.this, CutPictureAty.class);
                    intent.putExtra("path", PhotoWallAdapter.mSelectedImage.get(0));
                    startActivityForResult(intent, MyApplication.CUT);
                } else {
                    Intent intent = new Intent();
                    intent.putStringArrayListExtra(KEY_SELECTED_PHOTOS, (ArrayList<String>) PhotoWallAdapter.mSelectedImage);
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }
        });
        mBackBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }

    private void initViews() {
        diyView = (View) findViewById(R.id.diyview);
        mBarView = (RelativeLayout) findViewById(R.id.layout_view);
        mTopbar = (RelativeLayout) findViewById(R.id.layout_top_actionbar);
        mBottombar = (RelativeLayout) findViewById(R.id.layout_bottom_actionbar);
        mBackBtn = (ImageView) findViewById(R.id.iv_back);
        tvComplete = (TextView) findViewById(R.id.tv_commit);
        tvComplete.setPadding(getResources().getDimensionPixelSize(R.dimen.x14), 0, getResources().getDimensionPixelSize(R.dimen.x14), 0);
        layout_bottom_actionbar = (RelativeLayout) findViewById(R.id.layout_bottom_actionbar);
        tvChooseAblum = (Button) findViewById(R.id.btn_choose_dir);
        tvPreview = (TextView) findViewById(R.id.tv_preview);
        tvSelected = (TextView) findViewById(R.id.tv_selectbox);
        setFullScreen(false);
    }

    @Override
    public void onBackPressed() {
        setFullScreen(false);
        if (mPagerFragment != null && mPagerFragment.isVisible()) {
            mPagerFragment.runExitAnimation(new Runnable() {

                @Override
                public void run() {
                    if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
                        getSupportFragmentManager().popBackStack();
                    }
                }
            });
            tvChooseAblum.setVisibility(View.VISIBLE);
            tvPreview.setVisibility(View.VISIBLE);
            tvSelected.setVisibility(View.GONE);
            //显示顶部和底部布局
            mTopbar.setVisibility(View.VISIBLE);
            mBottombar.setVisibility(View.VISIBLE);
            //刷新选择的数据
            mPickerFragment.refreshData();
        } else {
            super.onBackPressed();
        }
    }

    public void addPhotoPagerFragment(PhotoViewFragment photoPagerFragment) {
        this.mPagerFragment = photoPagerFragment;
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.container, this.mPagerFragment)
                .addToBackStack(null)
                .commit();
        tvChooseAblum.setVisibility(View.GONE);
        tvPreview.setVisibility(View.GONE);
        tvSelected.setVisibility(View.VISIBLE);
    }


    public void CameraResult(String path) {
        ArrayList<String> selectedPhotos = new ArrayList<>();
        selectedPhotos.add(path);
        Intent intent = new Intent();
        intent.putStringArrayListExtra(KEY_SELECTED_PHOTOS, selectedPhotos);
        setResult(RESULT_OK, intent);
        finish();
    }

    //修改当前 Activity 的显示模式，hideStatusBarBackground :true 全屏模式，false 着色模式
    public void setFullScreen(boolean flag) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            int top = Common.getStatusBarHeight(this);
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            lp.height = top;
            diyView.setBackgroundColor(ContextCompat.getColor(this, R.color.background));
            Window window = getWindow();
//            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            if (flag) {
                /**设置全屏**/
                this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                        WindowManager.LayoutParams.FLAG_FULLSCREEN);
//                window.setStatusBarColor(ContextCompat.getColor(this, R.color.transparent));
                diyView.setLayoutParams(lp);
                diyView.setVisibility(View.GONE);
            } else {
                /**退出全屏**/
                this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
//                window.setStatusBarColor(ContextCompat.getColor(this, R.color.background));
                diyView.setLayoutParams(lp);
                diyView.setVisibility(View.VISIBLE);
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            int top = Common.getStatusBarHeight(this);
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            lp.height = top;
            diyView.setBackgroundColor(ContextCompat.getColor(this, R.color.background));
            Window window = getWindow();
//            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            if (flag) {
                /**设置全屏**/
                this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                        WindowManager.LayoutParams.FLAG_FULLSCREEN);
                window.setStatusBarColor(ContextCompat.getColor(this, R.color.transparent));
                diyView.setLayoutParams(lp);
                diyView.setVisibility(View.GONE);
            } else {
                /**退出全屏**/
                this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
                window.setStatusBarColor(ContextCompat.getColor(this, R.color.background));
                diyView.setLayoutParams(lp);
                diyView.setVisibility(View.VISIBLE);
            }
        }
    }

    public void checkPermission(String[] perms) {
        //显示进度条
        if (ContextCompat.checkSelfPermission(this, perms[0])
                != PackageManager.PERMISSION_GRANTED) {
            if (perms[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                //申请WRITE_EXTERNAL_STORAGE权限
                ActivityCompat.requestPermissions(this, perms, MyApplication.WRITE_EXTERNAL_STORAGE);
            } else if (perms[0].equals(Manifest.permission.CAMERA)) {
                //申请WRITE_EXTERNAL_STORAGE权限
                ActivityCompat.requestPermissions(this, perms, MyApplication.CAMERA_PERMISSION);
            }
        } else {
            if (perms[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                //获取当前文件夹下的图片列表
                getImages();
            } else if (perms[0].equals(Manifest.permission.CAMERA)) {
                try {
                    Intent intent = captureManager.dispatchTakePictureIntent();
                    startActivityForResult(intent, ImageCaptureManager.REQUEST_TAKE_PHOTO);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case MyApplication.WRITE_EXTERNAL_STORAGE://同意了操作内存权限
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    getImages();
                } else {
                    //用户点击拒绝后，弹出dialog，点击“确定”会去设置界面
                    if (appSettingsDialog != null) {
                        if (!appSettingsDialog.isShowing()) {
                            appSettingsDialog.show();
                        }
                    } else {
                        appSettingsDialog = new AppSettingsDialog.Builder(this, "点击确定去设置界面设置存储空间权限")
                                .setTitle("提示")
                                .setPositiveButton("确定")
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        appSettingsDialog.dismiss();
                                        finish();
                                    }
                                })
                                .setRequestCode(MyApplication.WRITE_EXTERNAL_STORAGE)
                                .setCancelListener(new DialogInterface.OnCancelListener() {
                                    @Override
                                    public void onCancel(DialogInterface dialog) {
                                        finish();
                                    }
                                })
                                .build();
                        appSettingsDialog.show();
                        isShowDialog = true;
                    }
                }
                break;
            case MyApplication.CAMERA_PERMISSION:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    try {
                        Intent intent = captureManager.dispatchTakePictureIntent();
                        startActivityForResult(intent, ImageCaptureManager.REQUEST_TAKE_PHOTO);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    appSettingsDialog = new AppSettingsDialog.Builder(this, "点击确定去设置界面设置相机权限")
                            .setTitle("提示")
                            .setPositiveButton("确定")
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    appSettingsDialog.dismiss();
                                }
                            })
                            .setRequestCode(MyApplication.CAMERA_PERMISSION)
                            .setCancelListener(new DialogInterface.OnCancelListener() {
                                @Override
                                public void onCancel(DialogInterface dialog) {
                                }
                            })
                            .build();
                    appSettingsDialog.show();
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == ImageCaptureManager.REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
            if (captureManager == null) {
                captureManager = new ImageCaptureManager(this);
            }
            captureManager.galleryAddPic();
            if (isShowCut) {//需要裁剪
                Intent intent = new Intent(PhotoPickerActivity.this, CutPictureAty.class);
                intent.putExtra("path", captureManager.getCurrentPhotoPath());
                startActivityForResult(intent, MyApplication.CUT);
            } else {
                if (mImageFolders.size() > 0) {
                    String path = captureManager.getCurrentPhotoPath();//获取拍照的手机照片
                    CameraResult(path);
//                PhotoDirectory directory = directories.get(INDEX_ALL_PHOTOS);//是否及时更新拍照的手机照片到相册中
//                directory.getPhotos().add(INDEX_ALL_PHOTOS, new Photo(path.hashCode(), path));
//                directory.setCoverPath(path);
//                mAdapter.notifyDataSetChanged();
                }
            }
        } else if (requestCode == MyApplication.CUT && resultCode == RESULT_OK) {//裁剪图片回调
            if (data != null) {
                final String imagePath1 = data.getStringExtra("imgpath");
                if (!Common.empty(imagePath1)) {
                    CameraResult(imagePath1);
                }
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (TextUtils.isEmpty(firstDirName)) {
            if (!isShowDialog) {
                checkPermission(perms);
            } else {
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    if (appSettingsDialog != null) {
                        if (!appSettingsDialog.isShowing()) {
                            appSettingsDialog.show();
                        }
                    } else {
                        appSettingsDialog = new AppSettingsDialog.Builder(this, "点击确定去设置界面设置存储空间权限")
                                .setTitle("提示")
                                .setPositiveButton("确定")
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        appSettingsDialog.dismiss();
                                        finish();
                                    }
                                })
                                .setRequestCode(MyApplication.WRITE_EXTERNAL_STORAGE)
                                .setCancelListener(new DialogInterface.OnCancelListener() {
                                    @Override
                                    public void onCancel(DialogInterface dialog) {
                                        finish();
                                    }
                                })
                                .build();
                        appSettingsDialog.show();
                    }
                } else {
                    if (appSettingsDialog != null) {
                        if (appSettingsDialog.isShowing()) {
                            appSettingsDialog.dismiss();
                        }
                    }
                    getImages();
                }
            }
        }
    }


    /**
     * 扫描图片
     */
    public void getImages() {
        if (!Environment.getExternalStorageState().
                equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(this, "no external storage", Toast.LENGTH_SHORT).show();
            return;
        }

        //显示进度条
        if (mProgressDialog == null)
            mProgressDialog = ProgressDialog.show(this, null, "loading...");

        new Thread(new Runnable() {
            @Override
            public void run() {
                String firstImage = null;
                Uri mImgUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                ContentResolver mContentResolver = getContentResolver();

                Cursor mCursor = null;
                //只查询jpeg和png图片
                if (mDesireSearchPath == null) {
                    mCursor = mContentResolver.query(mImgUri, IMAGE_PROJECTION,
                            IMAGE_PROJECTION[3] + "=? or "
                                    + IMAGE_PROJECTION[3] + "=?",
                            new String[]{"image/jpeg", "image/png"},
                            IMAGE_PROJECTION[2] + " DESC");
                } else {
                    mCursor = mContentResolver.query(mImgUri, IMAGE_PROJECTION,
                            IMAGE_PROJECTION[4] + ">0 AND " + IMAGE_PROJECTION[0]
                                    + " like '%" + mDesireSearchPath + "%'", null,
                            IMAGE_PROJECTION[2] + " DESC");
                }

                while (mCursor.moveToNext()) {
                    //获得图片路径
                    String path = mCursor.getString(mCursor.
                            getColumnIndex(MediaStore.Images.Media.DATA));
                    //拿到第一张图片的路径
                    if (firstImage == null) {
                        firstImage = path;
                    }

                    //获取该图片的父路径名
                    File parentFile = new File(path).getParentFile();
                    if (parentFile == null)
                        continue;
                    String dirPath = parentFile.getAbsolutePath();
                    ImageFolder imageFolder = null;
                    //利用一个HashSet防止多次扫描同一个文件夹
                    if (mDirPaths.contains(dirPath)) {
                        continue;
                    } else {
                        mDirPaths.add(dirPath);
                        //初始化ImageLoader
                        imageFolder = new ImageFolder();
                        imageFolder.setDir(dirPath);
                        imageFolder.setFirstImagePath(path);
                        //获取优先显示的图片父路径名
                        if (mCursor.getPosition() == 0) {
                            mImgDir = parentFile;
                            firstDirName = imageFolder.getName();
                        }
                    }

                    int picSize = parentFile.list(new FilenameFilter() {
                        @Override
                        public boolean accept(File dir, String filename) {
                            if (filename.endsWith(".jpg")
                                    || filename.endsWith(".png")
                                    || filename.endsWith("jpeg"))
                                return true;
                            return false;
                        }
                    }).length;
                    //需要显示所有图片，修改此处
                    imageFolder.setCount(picSize);
                    mImageFolders.add(imageFolder);
                }
                mCursor.close();
                //扫描完成，辅助的HashSet释放内存
                mDirPaths = new HashSet<String>();
                mHandler.sendEmptyMessage(0x110);
            }
        }).start();
    }

    private String[] IMAGE_PROJECTION = {
            MediaStore.Images.Media.DATA,
            MediaStore.Images.Media.DISPLAY_NAME,
            MediaStore.Images.Media.DATE_ADDED,
            MediaStore.Images.Media.MIME_TYPE,
            MediaStore.Images.Media.SIZE,
            MediaStore.Images.Media._ID
    };

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            mProgressDialog.dismiss();
            if (mImgDir == null) {
//                Toast.makeText(PhotoPickerActivity.this, "no scanned images", Toast.LENGTH_SHORT).show();
                mPickerFragment.data2View(mImgDir);
                return;
            }
            tvChooseAblum.setText(firstDirName);
            //为View绑定数据
            mPickerFragment.data2View(mImgDir);
            //初始化展示文件夹的PopupWindow
            initListDirPopupWindow();
        }
    };


    private void initListDirPopupWindow() {
        mDirPopupWindow = new ListImageDirPopupWindow(mScreenWidth + 1, (int) (0.6 * mScreenHeight), mImageFolders, LayoutInflater.from(PhotoPickerActivity.this)
                .inflate(R.layout.list_folder, null));
        mDirPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                //设置背景颜色变暗
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1.0f;
                getWindow().setAttributes(lp);
            }
        });
        //设置选择文件夹的回调
        mDirPopupWindow.setOnPhotoDirSelected(new OnPhotoDirSelected() {
            @Override
            public void onSelected(ImageFolder folder) {
                mImgDir = new File(folder.getDir());
                //为View绑定数据
                mPickerFragment.data2View(mImgDir);
                tvChooseAblum.setText(folder.getName());
                mDirPopupWindow.dismiss();
            }
        });
    }

    @Override
    public void onDestroy() {
        if (mHandler != null) {
            mHandler.removeMessages(0x110);
            mHandler = null;
        }
        super.onDestroy();
    }
}
